package com.ybl.store.backend.service.impl.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybl.store.backend.dao.entity.user.ClerkDO;
import com.ybl.store.backend.dao.mapper.user.ClerkMapper;
import com.ybl.store.backend.dto.UserInfoDTO;
import com.ybl.store.backend.dto.req.user.clerk.ClerkSaveReqDTO;
import com.ybl.store.backend.dto.req.user.clerk.ClerkUpdateReqDTO;
import com.ybl.store.backend.dto.resp.user.clerk.ClerkNameRespDTO;
import com.ybl.store.backend.dto.resp.user.clerk.ClerkPageRespDTO;
import com.ybl.store.backend.service.user.ClerkService;
import com.ybl.store.common.constant.BanFlag;
import com.ybl.store.common.constant.DelFlag;
import com.ybl.store.common.constant.UserPermission;
import com.ybl.store.common.context.UserContext;
import com.ybl.store.common.convention.errorcode.BaseErrorCode;
import com.ybl.store.common.convention.exception.ClientException;
import com.ybl.store.common.entity.ListRespDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 店员服务层
 */
@Service
@RequiredArgsConstructor
public class ClerkServiceImpl extends ServiceImpl<ClerkMapper, ClerkDO> implements ClerkService {

    private static final String defaultPassword = "111111";

    private final ClerkMapper clerkMapper;

    @Override
    public void saveClerk(ClerkSaveReqDTO requestParam) {
        ClerkDO clerkDO = BeanUtil.toBean(requestParam, ClerkDO.class);
        clerkDO.setUsername(requestParam.getPhone());
        if (requestParam.getPassword() == null) {
            clerkDO.setPassword(defaultPassword);
        }

        int result = baseMapper.insert(clerkDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CLERK_SAVE_ERROR);
        }
    }

    @Override
    public void deleteClerkById(Long id) {
        int result = baseMapper.deleteById(id);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CLERK_DELETE_ERROR);
        }
    }

    @Override
    public void updateClerk(ClerkUpdateReqDTO requestParam) {
        int result = baseMapper.updateById(BeanUtil.toBean(requestParam, ClerkDO.class));
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CLERK_UPDATE_ERROR);
        }
    }

    @Override
    public void banClerk(Long id, Integer banFlag) {
        ClerkDO clerkDO = new ClerkDO();
        clerkDO.setId(id);
        clerkDO.setBanFlag(banFlag);
        int result = clerkMapper.updateById(clerkDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CLERK_BAN_ERROR);
        }
    }

    @Override
    public ListRespDTO<ClerkPageRespDTO> pageClerk(Integer pn, Integer ps, Long storeId, String name) {
        Page<ClerkPageRespDTO> page = new Page<>(pn, ps);
        QueryWrapper<ClerkDO> queryWrapper = Wrappers.query(ClerkDO.class)
                .eq(Objects.nonNull(storeId), "t_clerk.store_id", storeId)
                .like(Objects.nonNull(name), "t_clerk.name", name)
                .eq("t_clerk.del_flag", 0)
                .orderByAsc("t_clerk.name");
        List<ClerkPageRespDTO> clerkPageRespDTOList = clerkMapper.pageClerk(page, queryWrapper);

        queryWrapper = Wrappers.query(ClerkDO.class)
                .eq(Objects.nonNull(storeId), "t_clerk.store_id", storeId)
                .like(Objects.nonNull(name), "t_clerk.name", name)
                .eq("t_clerk.del_flag", 0);
        Long total = clerkMapper.selectCount(queryWrapper);

        return ListRespDTO.<ClerkPageRespDTO>builder()
                .total(total)
                .items(clerkPageRespDTOList)
                .build();
    }

    @Override
    public ListRespDTO<ClerkNameRespDTO> listClerkName() {
        Long clerkId = null;
        UserInfoDTO userInfoDTO = UserContext.get();
        if (Objects.equals(userInfoDTO.getPermission(), UserPermission.MANAGER)) {
            clerkId = userInfoDTO.getId();
        }
        else if (Objects.equals(userInfoDTO.getPermission(), UserPermission.CLERK)) {
            clerkId = userInfoDTO.getId();
        }

        LambdaQueryWrapper<ClerkDO> lambdaQueryWrapper = Wrappers.lambdaQuery(ClerkDO.class)
                .eq(Objects.nonNull(clerkId), ClerkDO::getId, clerkId)
                .eq(ClerkDO::getDelFlag, DelFlag.present)
                .eq(ClerkDO::getBanFlag, BanFlag.use)
                .orderByAsc(ClerkDO::getName);
        List<ClerkDO> clerkDOList = baseMapper.selectList(lambdaQueryWrapper);

        return ListRespDTO.<ClerkNameRespDTO>builder()
                .total((long) clerkDOList.size())
                .items(clerkDOList
                        .stream()
                        .map(each -> BeanUtil.toBean(each, ClerkNameRespDTO.class))
                        .toList())
                .build();
    }
}
